package com.gz.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtilsByDruid {
    private static DataSource ds;

    static {//初始化
        Properties properties = new Properties();
        try {
            properties.load(JdbcUtilsByDruid.class.getClassLoader().
                    getResourceAsStream("druid.properties"));
            ds= DruidDataSourceFactory.createDataSource(properties);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    //关闭连接
    //注意:数据库连接池中close并不是真的关闭连接
    //而是把使用的Connection放回连接池
    public static void close( ResultSet rs, Statement stmt, Connection conn) {
        try {
            if(rs!=null) {
                rs.close();
            }
            if(stmt!=null) {
                stmt.close();
            }
            if(conn!=null) {
                conn.close();//与原先jdbc原本的关闭方法不同，druid这里是放回连接池
                //涉及多态，这里的Connectcion是ds里面的Connection,调用的close方法是druid中的close方法
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
